package com.liao.liaowenlong;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import java.util.ArrayList;

public class BookDB extends SQLiteOpenHelper {
    public BookDB(@Nullable Context context) {
        super(context, "book", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table books(id Integer primary key autoincrement,bookname varchar(20)" +
                ",author varchar(20),sum Integer)");
        db.execSQL("insert into books(bookname,author,sum) values('aaa','aaaaa','123')");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public ArrayList<BookInfo> queryAllBook(SQLiteDatabase db) {
        Cursor cursor = db.query("books", null, null, null, null, null, null);
        ArrayList<BookInfo> books = new ArrayList<>();
        while (cursor.moveToNext()) {
            BookInfo bookInfo = new BookInfo();
            bookInfo.setName(cursor.getString(cursor.getColumnIndex("bookname")));
            bookInfo.setAuthor(cursor.getString(cursor.getColumnIndex("author")));
            bookInfo.setSum(cursor.getInt(cursor.getColumnIndex("sum")));
            books.add(bookInfo);
        }
        cursor.close();
        db.close();
        return books;
    }

    public long insertBook(SQLiteDatabase db, BookInfo bookInfo) {
        ContentValues values = new ContentValues();
        values.put("bookname", bookInfo.getName());
        values.put("author", bookInfo.getAuthor());
        values.put("sum", bookInfo.getSum());
        return db.insert("books", null, values);
    }

    public long deleteBook(SQLiteDatabase db, String bookName) {
        return db.delete("books", "bookname=?", new String[]{bookName});
    }
}
